retflag=true;

$.fn.profilePageCustomValidator=function(validatestring,submit,form){
	var flag = false;
	var flagInc = 0;
	var Requirederrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>This Field Is Required.</li></ul><span></span></div></div>'
 
	 if($(form).find(this).length>0 && submit){

		$(form).find(this).each(function(i){

	   flag=requiredfieldvalidtion($(this).val());	
	   
	  if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(Requirederrorstr);
	   flagInc++;$(this).focus();}
	 else {$(this).parent().find(".ketchup-errorPar").remove();
	 }
	 });
 
	 if(flagInc > 0)
		retflag = false;
	 else 
	  retflag = true;

	 }  
	$(this).live("blur",function(){
	  retflag=requiredfieldvalidtion($(this).val());
	if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(Requirederrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
}; 


$.fn.profilePageCustomValidatorNum=function(validatestring,submit,form){
	var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Numeric Value.</li></ul><span></span></div></div>'
    
	if($(form).find(this).length>0 && submit){
    $(form).find(this).each(function(i){
	
	flag=numberfieldvalidtion($(this).val());
	
	if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);flagInc++;}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}  
	
	$(this).blur(function(){
		
	retflag=numberfieldvalidtion($(this).val());
		if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
}; 

$.fn.profilePageCustomValidatorZip=function(validatestring,submit,form){
	var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Valid Zip Code.</li></ul><span></span></div></div>'
  
	if($(form).find(this).length>0 && submit){
    $(form).find(this).each(function(i){
	
	flag=zipcodevalidation($(form).find(this).val());
	
	if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);flagInc++;}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}  
	$(this).live("blur",function(){
	retflag=zipcodevalidation($(this).val());
	
		if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
}; 
	
$.fn.profilePageCustomValidatorPhone=function(validatestring,submit,form){
	var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error" style="width:125px;"><ul><li>Enter Valid Phone Number.</li></ul><span></span></div></div>'
  
	if($(form).find(this).length>0 && submit){
    $(form).find(this).each(function(i){
	
	flag=isPhoneValid($(form).find(this).val());
	
	if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);flagInc++;}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}  
	$(this).live("blur",function(){
	retflag=isPhoneValid($(this).val());
	
		if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
}; 
		
$.fn.profilePageCustomValidatoremail =function(validatestring,submit,form){
	var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error" style="top:-32px;"><ul><li>Enter Valid Email</li></ul><span></span></div></div>'
   	
	if($(form).find(this).length>0 && submit){
    $(form).find(this).each(function(i){
	
	flag=isEmailValid($(form).find(this).val());
	
	if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);flagInc++;}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}  
	$(this).live("blur",function(){
	retflag=isEmailValid($(this).val());
		if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
};

	
$.fn.profilePageCustomValidatorurl=function(validatestring,submit,form){
	var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Valid Url.</li></ul><span></span></div></div>'
  
	if($(form).find(this).length>0 && submit){
    $(form).find(this).each(function(i){
	
	flag=validWebsiteUrl($(form).find(this).val());
	
	if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);flagInc++;}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}  
	$(this).live("blur",function(){
	retflag=validWebsiteUrl($(this).val());
		if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
}; 



(function($){
    $.fn.quiggleDynamicFormAdd = function (templateBlock, placeHolder, indexBlock){
        $(this).click(function(){
//            alert("add address click " + templateBlock);
            var template = $(templateBlock);
            var indexField = $(indexBlock);
            var index = parseInt(indexField.text());
//            alert("index " + index);
            var templateClone = template.clone();
//            alert(templateClone.html());
            templateClone.html(templateClone.html().replace(/{index}/g, index));
			if($(placeHolder).attr("id")=="cert-placeholder"){
			 templateClone.html(templateClone.html().replace(/mandatoryfield-temp/g, "mandatoryfield"));
			}
            templateClone.attr('id', template.attr('id') + '-' + index)
            templateClone.removeClass('template');
            templateClone.insertBefore($(placeHolder));
//            alert(templateClone.html());
            templateClone.bindProfileEvents();
            indexField.text(index + 1);
			 var firstInput = $(":input:not(input[type=button],input[type=submit],button):visible:first", templateClone);
			firstInput.focus();

			//mandatoryfield-temp
          // $(".mandatoryfield").attr("data-validate","validate(required)");	
			//$("form").ketchup();		 
            
  if($(this).attr("id")=="addCert"){
  $(this).focus();
  setTimeout(function(){$(placeHolder).prev().find(".t-tip:first").focus()},250); }			
        });
    };
    $.fn.showFirstTemplate = function (templateBlock, placeHolder, indexBlock){
        var template = $(templateBlock);
        var indexField = $(indexBlock);
        var index = parseInt(indexField.text());

        var templateClone = template.clone();

        templateClone.html(templateClone.html().replace(/{index}/g, index));
        templateClone.attr('id', template.attr('id') + '-' + index)
        templateClone.removeClass('template');
        templateClone.insertBefore($(placeHolder));

       // templateClone.bindProfileEvents();
        indexField.text(index + 1);				
    }

    $.fn.multiSelectAdd = function(leftSelect, rightSelect){
    	$(this).click(function(){
			var duplInd=false;
            var pText = $(this).parent().find('.multi-select-add-text');
			var pVal = $.trim(pText.val());
			//var pVal = pText.val();
			
            if(pVal != null && pVal.length > 0){
            	$(rightSelect + ' option').each(function(){
					var rightOption = $(this);
                   
                    if(pVal.toLowerCase()==$(this).text().toLowerCase()){
                    	duplInd=true;
                    	alert("Duplicate entry");
                    }
                });
            	
            	$(leftSelect+' > option').each(function() {
					
            	    if(pVal.toLowerCase() == $(this).text().toLowerCase()){
                    	duplInd=true;
                       	alert("Option already exists.");
                    }
            	});
            	if(!duplInd){
            		 //var opt = new Option(pVal, pVal);
					 //$(rightSelect).append(opt);
					 
					var o = new Option(pVal, pVal);
					// jquerify the DOM object 'o' so we can use the html method
					$(o).html(pVal);
					$(rightSelect).append(o);

					 				 
            	}

            }
            pText.val('');
        });
    };
    $.fn.bindProfileEvents = function(){
    	$(this).attr("id");
        $(this).find('.public-private-button').each(function(){
        	$(this).attr("id");
            $(this).click(function(){            	
                if($(this).hasClass('public')){
                    $(this).closest(".public-private-switch").find('.p-p-input').val('false');
                    $(this).removeClass('public').html('Private');
                    $(this).closest(".toolTip-cust").find(".toolTip-caption").html("Information is private and NOT shared, click space bar to toggle between private and public");
					$(this).closest(".toolTip-cust").find(".toolTip-caption").css({"top":"-65px","width":"180px"}).show();
                }
                else{
                    $(this).closest(".public-private-switch").find('.p-p-input').val('true');
                    $(this).addClass('public').html('Public');
                    $(this).closest(".toolTip-cust").find(".toolTip-caption").html("Share with other members only, click space bar to toggle between private and public");
					$(this).closest(".toolTip-cust").find(".toolTip-caption").css({"top":"-65px","width":"180px"}).show();
                }
                
         /*      var spantag="<span class='toolTip-caption'>"+$(this).attr("title")+"</span>";
                $(this).wrap("<span class='toolTip-cust'></span>");
                $(this).before(spantag);
                $(this).removeAttr("title");*/
				
            })
        });

        $(this).find('.delete-button').each(function(){

            $(this).click(function(){
                $(this).parent().find('.delete-input').val('true');
                var template = $(this).attr("template");
			if (confirm("Are you sure you want to delete?")) {
				//$(this).remove();
				$('#'+template).hide();
			}


                //alert('template ' + template);
                //$('#'+template).hide();
            })
        });
    };



})(jQuery);

function clearLeftSelection(leftSelect, rightSelect, customAdd){

	$(customAdd).multiSelectAdd(leftSelect, rightSelect);
    $(rightSelect + ' option').each(function(){
        var rightOption = $(this);
		$(leftSelect + ' option').each(function(i) {
			if( $(this).val() == rightOption.val()){
                rightOption.text($(this).text());
                $(this).remove();
            }
        });
    });
};
$(document).ready(function(){

	$("#contactCheckBox-All").live("click",function(){
	$('.checkBoxContactId').attr("checked",$(this).is(":checked"));	
	});
	$(".sendProfile").click(function(){
		$("#accountreceivableProfilesDialog").dialog({
		height: 300,
		width: 420,
		modal: true,
		title:"Account Receivable Contacts",
		hide: 'fold',
        show: 'blind',
			buttons: {
			"Add New": function() {
			addNewContactDetailsRow();
			},
			"Send":function(){sendMailToAccReceivables();},
			"Cancel": function() {
						
				$(this).dialog('close');
			}
			},
		
	});
	getAccountreceivableProfilesDetails();
	});

		$("#instructionsHideLink").live("click",function(){

		   $("#contentIns").hide();
		   $("#instrutionsSpan").html("<a title='click here to show the instructions' id='instructionsShowLink' style='background:#E3F2FF;' href='javascript:{}'><img  id='instructionsDownarrowimg' src='images/downarrow.png' width='10' height='9' alt='Hide' /></a>");
		});
						

		$("#instructionsShowLink").live("click",function(){
			$("#contentIns").show();
			$("#instrutionsSpan").html("<a title='click here to hide the instructions' id='instructionsHideLink' style='background:#E3F2FF;' href='javascript:{}'><img  id='instructionsuparrowimg' src='images/uparrow.png' width='10' height='9' alt='Hide' /></a>");

		});

	$(".tip").each(function(){
				var spantag="<span class='toolTip-caption'>"+$(this).attr("title")+"</span>";
				$(this).wrap("<span class='toolTip-cust'></span>");
				$(this).before(spantag);    
				$(this).removeAttr("title");
			  });
			  
/*
$(".public-private-button").live("focusin",function(){

$(this).closest(".toolTip-cust").find(".toolTip-caption").show("fast");
});
$(".public-private-button").live("focusout",function(){

$(this).closest(".toolTip-cust").find(".toolTip-caption").hide("fast");
}); */


$(".delete-input").each(function(){

if($(this).val()=='true')
$(this).closest(".profile-block").hide();

});
	$("input").live("focusin",function(){

       $(this).parent().find(".ketchup-errorPar").remove();
		
		
    });

			
	
	currentAction = 2;
	
	$("#my-profile-form :input").live("keypress",function() {
		$('#changeInd').val(true);
		isProfileChanged = true; 
		isFormFieldChanged = true;
	});
	
	

	
	$(".add-button").live("click",function(){
		$('#changeInd').val(true);
		isProfileChanged = true; 
		isFormFieldChanged = true;
	});
	
   $(".delete-button").live("click",function(){
	   $('#changeInd').val(true);
	   isProfileChanged = true; 
	   isFormFieldChanged = true;
	});
    $(".public-private-switch").live("click",function(){
    	$('#changeInd').val(true);
    	isProfileChanged = true; 
		isFormFieldChanged = true;
	});
    
    $("select").change(function() {
    	
    	$('#changeInd').val(true);
		isProfileChanged = true; 
		isFormFieldChanged = true;
	});
	
	
	

//alert($("#easyDefault").is(':checked'));
//alert($("#regularDefault").is(':checked'));
	$(".mandatoryfield").profilePageCustomValidator("required",false);
	$(".numberVal").profilePageCustomValidatorNum("number",false);
	$(".zipval").profilePageCustomValidatorZip("zip",false);
	$(".phoneval").profilePageCustomValidatorPhone("Phone",false);
	$(".emailval").profilePageCustomValidatoremail("email",false);
	$(".urlinput").profilePageCustomValidatorurl("url",false);


//navigating without saving
var warnMessage = "You have unsaved changes on this page!";
$('.unload').click(function(e) {
		
	window.onbeforeunload = null;
	 });

    $('input:not(:button,:submit),textarea,select,checkbox').keypress(function () {
        window.onbeforeunload = function () {
		 if (isProfileChanged || isFormFieldChanged) return warnMessage;
        }
    });
	
	$('.public-private-button').click(function(e){
		
		 window.onbeforeunload = function () {
            if (warnMessage != null) return warnMessage;
        }
	});
    $('input:submit').click(function(e) {
        warnMessage = null;
    });

//end of navigating without saving



  $("#firstName").focus();
 
 $(".profile-block,.groupBox").attr("tabindex","0");
 

			/* $(".t-tip").each(function(){
				var spantag="<span class='toolTip-caption'>"+$(this).attr("title")+"</span>";
				if($(this).prop("tagName")=="TEXTAREA"){spantag="<span class='toolTip-caption' style='top:-120px;'>"+$(this).attr("title")+"</span>";}
	 		$(this).wrap("<span class='toolTip-cust'></span>");
				$(this).before(spantag);    
				$(this).removeAttr("title");
			  });
			  
			
			$("textarea,.multi-select-add-text").closest(".toolTip-cust").find(".toolTip-caption").css("top","-80px"); */
			$(".certificateTypeOther").live("focusin",function(){
			      $(this).closest(".toolTip-cust").find(".toolTip-caption").show("fast");
				   
            });
			$(".certificateTypeOther").live("focusout",function(){			
			       $(this).closest(".toolTip-cust").find(".toolTip-caption").hide("fast");
            }); 
           

	//$(".mandatoryfield").attr("data-validate","validate(required)");
	//$(".emailval").customValidator("validate(email)");
	//$(".urlinput").customValidator("validate(curl)");
	//$(".numberVal").customValidator("validate(price)");
	//$(".phoneval").customValidator("validate(phone)");
	//$(".zipval").customValidator("validate(zip)");
		
		//$("form").ketchup();
 
  if($("#locIndex").text()=="0")
	  $(this).showFirstTemplate("#locTemplate", "#loc-placeholder", "#locIndex");
  
  /** AVAILIBILITY SCHEDULE TIME FORMAT **/
  $(".time:even").timeEntry( {
	show24Hours: true, // True to use 24 hour time, false for 12 hour (AM/PM) 
	defaultTime: '00:00AM'
  });
    $(".time:odd").timeEntry( {
	show24Hours: true, // True to use 24 hour time, false for 12 hour (AM/PM) 
	defaultTime: '00:00PM'
  });
  $(".schedule").timeEntry( {
	show24Hours: true // True to use 24 hour time, false for 12 hour (AM/PM) 
  });

  
  
  var hrtype=$("#hourType").val();
  if(hrtype==1){$(".time").timeEntry('change', 'show24Hours', false); $(".schedule").timeEntry('change', 'show24Hours', false);}
  else{$(".time").timeEntry('change', 'show24Hours', true);$(".schedule").timeEntry('change', 'show24Hours', true);}
  
  $("#hourType").change(function(){
    if($(this).val()==1) {$(".time").timeEntry('change', 'show24Hours', false);}
	else if($(this).val()==2) {$(".time").timeEntry('change', 'show24Hours', true); }
	});
	
	/** number validations
	$('#skillAdminHrs').attr("pattern","^[0-9]+$");
	$('#regSkillScope').attr("pattern","^[0-9]+$");
	$('#regSkillProof').attr("pattern","^[0-9]+$");
	$('#denseSkillScope').attr("pattern","^[0-9]+$");
	$('#denseSkillProof').attr("pattern","^[0-9]+$");
	$('#easySkillScope').attr("pattern","^[0-9]+$");
	$('#easySkillProof').attr("pattern","^[0-9]+$");
	
 
  
  /** Email ValiDations 
  $('.emailval').attr("pattern","^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$");
 /** AVAILIBILITY SCHEDULE **/ 
	
	var timeZoneArray = ["A","ADT","AFT","AKDT","AKST","ALMT","AMST","AMT","ANAST","ANAT",
		"AQTT","ART","AST","AZOST","AZOT","AZST","AZT","B","BNT","BOT","BRST","BRT","BST",
		"BTT","C","CAST","CAT","CCT","CDT","CEST","CET","CHADT","CHAST","CKT","CLST",
		"CLT","COT","CST","CVT","CXT","ChST","D","DAVT","E","EASST","EAST","EAT","ECT",
		"EDT","EEST","EET","EGST","EGT","EST","ET","F","FJST","FJT","FKST","FKT","FNT",
		"G","GALT","GAMT","GET","GFT","GILT","GMT","GST","GYT","H","HAA","HAC","HADT","HAE",
		"HAP","HAR","HAST","HAT","HAY","HKT","HLV","HNA","HNC","HNE","HNP","HNR","HNT","HNY",
		"HOVT","I","ICT","IDT","IOT","IRDT","IRKST","IRKT","IRST","IST","JST","K","KGT",
		"KRAST","KRAT","KST","KUYT","L","LHDT","LHST","LINT","M","MAGST","MAGT","MART",
		"MAWT","MDT","MESZ","MEZ","MHT","MMT","MSD","MSK","MST","MUT","MVT","MYT",
		"N","NCT","NDT","NFT","NOVST","NOVT","NPT","NST","NUT","NZDT","NZST",
		"O","OMSST","OMST","P","PDT","PET","PETST","PETT","PGT","PHOT","PHT",
		"PKT","PMDT","PMST","PONT","PST","PT","PWT","PYST","PYT","Q","R","RET",
		"S","SAMT","SAST","SBT","SCT","SGT","SRT","SST","T","TAHT","TFT","TJT",
		"TKT","TLT","TMT","TVT","U","ULAT","UYST","UYT","UZT","V","VET","VLAST",
		"VLAT","VUT","W","WAST","WAT","WDT","WEST","WEST","WESZ","WET","WEZ","WFT",
		"WGST","WGT","WIB","WIT","WITA","WST","WST","WST","WT","X","Y","YAKST",
		"YAKT","YAPT","YEKST","YEKT","Z"];

	$(".timeZone").live("focus", function(){

	$(".timeZone").autocomplete({

	source: function(req, responseFn) {
        var re = $.ui.autocomplete.escapeRegex(req.term);
        var matcher = new RegExp( "^" + re, "i" );
        var a = $.grep( timeZoneArray, function(item,index){
            return matcher.test(item);
        });
        responseFn( a );
    }
});
}); 

$(".timeZone").autocomplete({
source: function(req, responseFn) {
        var re = $.ui.autocomplete.escapeRegex(req.term);
        var matcher = new RegExp( "^" + re, "i" );
        var a = $.grep( timeZoneArray, function(item,index){
            return matcher.test(item);
        });
        responseFn( a );
    }
});


	$("#oa").find("br:first").hide();	
	
    $("#addAddress").quiggleDynamicFormAdd("#addressTemplate", "#address-placeholder", "#addressIndex");
    $("#addEmail").quiggleDynamicFormAdd("#emailTemplate", "#email-placeholder", "#contactIndex");
    $("#addPhone").quiggleDynamicFormAdd("#phoneTemplate", "#phone-placeholder", "#contactIndex");
    $("#addEmergencyContact").quiggleDynamicFormAdd("#emergencyContactTemplate", "#emergency-contact-placeholder", "#emergencyContactIndex");
    $("#addCert").quiggleDynamicFormAdd("#certTemplate", "#cert-placeholder", "#certIndex");
    $("#addLoc").quiggleDynamicFormAdd("#locTemplate", "#loc-placeholder", "#locIndex");
	$("#addEmailAddress").quiggleDynamicFormAdd("#emailaddressTemplate", "#emailaddress-placeholder", "#emailaddressIndex");
	$("#addPhoneAddress").quiggleDynamicFormAdd("#phoneaddressTemplate", "#phoneaddress-placeholder", "#phoneaddressIndex");
	
   $(this).bindProfileEvents();
    $(".phoneSelect option[value='2']").remove();
    $(".phoneSelect option[value='8']").remove();
    
    $(".emailSelect option[value='1']").remove();
    $(".emailSelect option[value='3']").remove();
    $(".emailSelect option[value='4']").remove();
    $(".emailSelect option[value='5']").remove();
    $(".emailSelect option[value='6']").remove();
    $(".emailSelect option[value='7']").remove();
    
    $(".low input[type='button']").click(function(){
        var arr = $(this).attr("name").split("2");
        var from = arr[0];
        var to = arr[1];
        $("#" + from + " option:selected").each(function(){
			$("#" + to).append($(this).clone());
            $(this).remove();
        });
    });

    $("#my-profile-form").submit(function(){
        $('.multi-select-right option').each(function(i) {
            $(this).attr("selected", "selected");
        });

    });


			
      $(".cancel").click(function(){
           
       /* if(confirm("Do u want to Cancel")) {
		 
		window.location.href = '/quiggle/qgl-log-pending.action';
		}*/
		if(isProfileChanged){
$('#showconfirmDiv').html("Do you want to cancel without saving?");
 $('#showconfirmDiv').dialog({
		height: 180,
		width: 360,
		modal: true,
		title:"Save or Discard",
		hide: 'fold',
        show: 'blind',
		buttons: {
			"Yes": function() {	
			   isProfileChanged =false;
				isFormFieldChanged=false;
				window.location.href = '/quiggle/qgl-log-pending.action';
				
				
			},
			"No": function() {
						
				$(this).dialog('close');
			}
		}

		});} else window.location.href = '/quiggle/qgl-log-pending.action';
	});

    
	clearLeftSelection("#schools-left", "#schools-right", "#school-add");
    clearLeftSelection("#cats-left", "#cats-right", "#cat-add");
    clearLeftSelection("#os-left", "#os-right", "#os-add");
    clearLeftSelection("#jobs-left", "#jobs-right", "#job-add");
    clearLeftSelection("#specialities-left", "#specialities-right", "#specialty-add");
    clearLeftSelection("#hobbies-left", "#hobbies-right", "#hobby-add");
    clearLeftSelection("#expertises-left", "#expertises-right", "#expertise-add");
    
    $('.time-picker').timepicker({});

$("input:radio").focusin(function(){
//$(this).wrap("<span style='background:#fffff0;padding:3px;'></span>")
$(this).closest(".radioclass").addClass("radiofocusclass");
})
$("input:radio").focusout(function(){

$(this).closest(".radioclass").removeClass("radiofocusclass");
})
    $("#my-profile-form").submit(function(){
	$("#ui-tips").html('');
    $("#ui-tips").hide();
  	

    
	checkBoxFlag=$('input:radio[name="userProfile.defaultSkillType"]').is(':checked');
	var isMandatory=false;
      
	
	$(".mandatoryfield").profilePageCustomValidator("required",true,this);
    
	if(retflag)	
	$(".numberVal").profilePageCustomValidatorNum("number",true,this);

    if(retflag)	
	$(".zipval").profilePageCustomValidatorZip("zip",true,this);
	if(retflag)	
	$(".phoneval").profilePageCustomValidatorPhone("Phone",true,this);

	if(retflag)
	$(".emailval").profilePageCustomValidatoremail("email",true,this);

	isMandatory=retflag;

	if(checkBoxFlag==false)
	{
		
	  updateTips("Set as Default" + " is a mandatory field", isMandatory, true);
	  $("#ui-tips").show();
	  $('#regularDefault').focus();
	  isMandatory = false;
	   
    }


	if(isMandatory){var hrtype=$("#hourType").val();
   if(hrtype==1){$(".time").timeEntry('change', 'show24Hours', true);}
			  else{$(".time").timeEntry('change', 'show24Hours', true);}}
			  if(isMandatory)  warnMessage = null;
					return isMandatory;
	});
    
    $(".autoCert").autocomplete({
   	 source:categoriesCert
    });
    
    $("#addCert").click(function(){
	$(".autoCert").autocomplete({ source:categoriesCert });
	});
    
    $("#addAddress").click(function(){
    	 $(".usaStates").autocomplete({
    			source: usaStates
    		});

	});
    
    $(".usaStates").autocomplete({
		source: usaStates
	});


	$('.certificateType').each(function(i){

		var text = $(this).find("option:selected").text();
		if(text == "Other"){
			$(this).closest('.profile-block').find('.hiddenTextBox').removeClass('hide');
			$(this).closest('profile-block').find('.hiddenTextBox').addClass('show');
	    }
		else{
			$(this).closest('.profile-block').find('.hiddenTextBox').removeClass('show');
			$(this).closest('.profile-block').find('.hiddenTextBox').addClass('hide');
	}	

	});

	
	$('.certificateType').live("change",function(){
	
		var text = $(this).find("option:selected").text(); 
			if(text == "Other"){
			$(this).closest('.profile-block').find('.hiddenTextBox').removeClass('hide');
			$(this).closest('.profile-block').find('.hiddenTextBox').addClass('show');
			$(this).closest('.profile-block').find('.certificateTypeOther').focus();
	    }
		else{
			$(this).closest('.profile-block').find('.hiddenTextBox').removeClass('show');
			$(this).closest('.profile-block').find('.hiddenTextBox').addClass('hide');
	}	

	});
		
	$(".time:eq(1)").blur(function(){
	if($("#timeschedule").is(":checked")){$("#timeschedule").trigger("click");$("#timeschedule").attr("checked",true);$("#saturdayFrom").focus();}
	});

	$("#timeschedule").click(function()
	{
 		fromArr = ["#mondayFrom","#tuesdayFrom","#wednesdayFrom","#thursdayFrom","#fridayFrom"];
 		toArr = ["#mondayTo","#tuesdayTo","#wednesdayTo","#thursdayTo","#fridayTo"];
 		fromTime =0;
 		toTime=0;
 		fromTimeArr = ["#mondayFromselect","#tuesdayFromselect","#wednesdayFromselect","#thursdayFromselect","#fridayFromselect"];
 		toTimeArr = ["#mondayToselect","#tuesdayToselect","#wednesdayToselect","#thursdayToselect","#fridayToselect"];
 		fromTimeStr = null;
 		toTimeStr = null;
		
		if($(this).is(":checked"))
		{

			for(i=0;i<fromArr.length;i++)
			{
			if($(fromArr[i]).length > 0 && fromTime< 2) 
			{
				fromTime = $(fromArr[i]).val();
				//fromTimeStr=$(fromTimeArr[i]).val();
			}
		
			if($(toArr[i]).length > 0 && toTime< 2)
			{
				toTime = $(toArr[i]).val();
				//toTimeStr=$(toTimeArr[i]).val();
			}

		}
      /*
		if(fromTime == "" || toTime == "")
		{
			$("#availabilityScheErrorSpan").html("Please Enter From and to Time.");
			$("#timeschedule").attr('checked', false);
			return;
		}
		else
			$("#availabilityScheErrorSpan").html("");*/
      if(fromTime != "" && toTime != "")
		for(i=0;i<fromArr.length;i++)
		{
			$(fromArr[i]).val(fromTime);
			//$(fromTimeArr[i]).val(fromTimeStr);
			$(toArr[i]).val(toTime);
			//$(toTimeArr[i]).val(toTimeStr);
		}		
  
	}
});

// key board events to public private switch
 $(".public-private-switch").live("keypress",function(event) {
 // alert( event.which);
  if (event.which == 32 ) {
	   event.preventDefault();
  $(this).find('.public-private-button').trigger("click");
 }
     });
	 $(".public-private-switch").focusout(function(){
$(this).find(".toolTip-caption").hide();
  });	 
  $(".public-private-switch").focusin(function(){
$(this).find(".toolTip-caption").css({"top":"-65px","width":"180px"}).show();
  });	 

// public Private lost focus to my hours  
 $(".public-private-switch:first").focusout(function(){
 
$("#regSkillScope").focus();
  });
  
  $(".add-button, .delete-button, .p-button").attr("tabindex","0");
  
  var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
  if(is_chrome==true){
  
  $(".add-button, .delete-button, .p-button").live("keydown",function(event) {
  if (event.which == 32 ) {
 return false;
  }
  });
  
  $(".add-button, .delete-button, .p-button").live("keyup",function(event) {
	
  	if (event.which == 32 ) {
	$(this).trigger("click");
	}
    });
  }
  
  else{
   $(".add-button, .delete-button, .p-button").live("keypress",function(event) {
 
  if (event.which == 32 ) {
  event.preventDefault();
  $(this).trigger("click");
  }
  });
  }

/// My Hours Lost Focus to Main Form  
$("#skillAdminHrs").blur(function(){
//alert($("[id|='phoneTemplate']:visible").not(".template").length);
  if($("[id|='phoneTemplate']:visible").not(".template").length>0){$("[id|='phoneTemplate']:visible").not(".template").first().find("select:first").focus();}
  else{$("#addPhone").focus();}
  /*else if($("[id|='emailTemplate']:visible").not(".template").length>0){$("[id|='emailTemplate']:visible").not(".template").first().find("select:first").focus();}
  else if($("[id|='addressTemplate']:visible").not(".template").length>0){$("[id|='addressTemplate']:visible").not(".template").first().find("input").not(":hidden ").first().focus();}
  
   else if($("[id|='emergencyContactTemplate']:visible").not(".template").length>0){$("[id|='emergencyContactTemplate']:visible").not(".template").first().find("select:first").focus();}
  else if($("[id|='certTemplate']:visible").not(".template").length>0){$("[id|='certTemplate']:visible").not(".template").first().find("select:first").focus();}
  else
  $("#schools-left").focus();*/
  
   });

$('.close').live("click",function(){
	   $('#successDiv').hide();
	   	});
setTimeout("closesuccessdiv()",5000);  
});

function closesuccessdiv(){
   $('#successDiv').hide();
}

function validateHoursToPerform(scopeid,proofid)
{
	var flag=false;
	if($(scopeid).val()>0 && $(proofid).val()>0 ){flag=true;}
		return flag;
}

function validateAdministrativHours(skillAdminHrsId)
{
	var flag=false;
	if($(skillAdminHrsId).val() > 0)
	{
		flag=true;
	}
	return flag;
}

function expandSelectBox(id){
	
	var size = $('#'+id+' :selected').text().length;
	
	if(size > 27){
	$('#'+id).css('width','325px');
	$('#schools-right').css('width','325px');
	}
	
}

function requiredfieldvalidtion(eleVal){
  var flag=false;
  //if(eleVal.trim()=="")
  var eleVal=$.trim(eleVal);
  if(eleVal=="")
	flag=false;
  else
	flag=true;
			
  return flag;
		}


 function numberfieldvalidtion(eleVal)
 {
	var flag=false;
	  eleVal = $.trim(eleVal);

	 if(eleVal == "")
		flag=false;
		
	 else if(!isNaN(eleVal))
	  flag=true;
	 else 
	   flag= false;
	return flag;	
	}

	

	function requiredCheckBoxValidation()
	{
		var flag=false;
		if($("#easyDefault").is(':checked') ||$("#denseDefault").is(':checked') || $("#regularDefault").is(':checked'))
		 flag = true;
		return flag;

	}

	function zipcodevalidation(eleVal){
		var flag=false;
		var value =eleVal.replace(/^\s+|\s+$/g,"");
		var zipcode_regex = /^\d{5}$/;
		//var zip_canada=/^[a-zA-Z]\d{1}[a-zA-Z](\-| |)\d{1}[a-zA-Z]\d{1}$/;
		var zip_canada=/^[a-z][0-9][a-z]\s*?[0-9][a-z][0-9]$/i;
		var zipUS=/^(\d{5})(-\d{4})?$/;
		
		if(value=="")
			flag=true;
		else if(zipcode_regex.test(value))
			flag=true;
		else if(zip_canada.test(value))
			flag=true;
			else if(zipUS.test(value))
			flag=true;
			
			//alert(zipcode_regex.test(eleVal) + "" + flag);}
			
		return flag;
		}

		function isPhoneValid(eleVal){
			
		var flag=false;
  		var phone1=/^\(?[0-9]?[-.()+]?([0-9]{0,9})\)?[-.()]?([0-9]{0,9})[-.()]?([0-9]{0,8})$/;
		var value =eleVal .replace(/([\s.?*+^$[\]!\\/\'@\"(){}-])/g, "");
                
		if(value=="" && eleVal == "")
			flag=true;
	
		else if(value.length > 9 && value.length < 16 &&!isNaN(value))
			flag=true;
		
		return flag;
  }

  function isEmailValid(eleVal){
		var flag=false;
	  var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{1,8}$/i;
	  if(eleVal == '')
		{
		 flag =true;
		}
		
	   else if (emailRegEx.test(eleVal))
		{	
		flag =true;
		}
			 
		return flag;
		 
	
		
	}

	function validWebsiteUrl(eleVal) {
			
	var pattern = /[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+\.[A-Z]{2,4}$)?$/i;
	if(eleVal == '')		
		{
			return true;
		}
	else if (pattern.test(eleVal)) {
           
        return true;
		
		} 
            
        return false;


	}

function getAccountreceivableProfilesDetails(){
	
	 $.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		type:'POST',
		url: 'my-profile.action?getAccountreceivableProfilesDetails',
		dataType: 'json',
		
		success: function(result){
		  
			 buildAccountreceivableProfilesDetails(result);
    
		 },
		error:function() { 
			  
		  }
	});
}

function buildAccountreceivableProfilesDetails(result){

$("#accReciContactDetailsInnerDiv").html('');

var str = '';
	str +='<div id="errorDiv"></div>';
	str +='<img id="ajaxImage" src=".../../images/billing-invoice/search.gif" style="float:right;display:none;margin-top: 3px; margin-right: 10px;" width="16" height="16" alt="processing your request" id="close"/>';
	str +='<div style="font-size:12px;font-weight:bold;margin-top: 4px;">';
	str +='<span><input type="checkbox" id="contactCheckBox-All"></span>';
	str +='<span style="margin-left: 11px;">Name</span>';
	str +='<span style="margin-left: 108px;">Email</span>';
	str +='</div>';

if(result != null && result.length > 0)
{
	
	for(i=0;i<result.length;i++)
	{	
		str +='<div style="font-size:12px;font-weight:bold;margin-top: 4px;">';
		str +='<input type="checkbox" id="" class="checkBoxContactId">';
		str +='<span style="margin-left: 9px; margin-right: 11px;">';
		if(result[i].contactName != null)
		   str +='<input class="contactName" type="text" value="'+result[i].contactName+'" id="contactName" /></span>';
		else
		   str +='<input class="contactName" type="text" value="" id="contactName" /></span>';
		str +='<span><input class="contactEmail contactEmailwidth" typr="text" value="'+result[i].contactEmail+'" id="email"/></span>';
		str +='</div>';
	}
	
	
}
 else if(result == null || result.length == 0)
 {
	str +='<div style="font-size:12px;font-weight:bold;margin-top: 4px;">';
	str +='<input type="checkbox" id="" class="checkBoxContactId">';
	str +='<span style="margin-left: 9px; margin-right: 11px;"><input type="text" class="contactName"></span>';
	str +='<span><input type="text" class="contactEmail contactEmailwidth"></span>';
	str +='</div>';
}

	$("#accReciContactDetailsInnerDiv").html(str);
}

function addNewContactDetailsRow()
{
	var str = '';
	str +='<div style="font-size:12px;font-weight:bold;margin-top: 4px;">';
	str +='<input type="checkbox" id="" class="checkBoxContactId">';
	str +='<span style="margin-left: 9px; margin-right: 11px;"><input type="text" class="contactName"></span>';
	str +='<span><input type="text" class="contactEmail contactEmailwidth"></span>';
	str +='</div>';
	$('#accReciContactDetailsInnerDiv').append(str);
	
}




function sendMailToAccReceivables()
{
	
	var delErrFlag = true;
	var emailEmptyFlag = false;
	var invalidEmailFlag = false;
	var contactNameEmptyFlag = false;
	var emailArray = new Array();
	var emailDupFlag = false;

	var str = '';
	var firstName = $("#firstName").val();
	var lastName = $("#lastName").val();
	var name = firstName +" "+lastName;
	var emai = "";
	var accountReceName = "";
	 var obj={
   			namesAndemailsArray:new Array()
   			
   	}

	$(".checkBoxContactId").each(function(){
		
	  if($(this).is(":checked"))
	  {
		accountReceName = $(this).closest("div").find(".contactName").val();
		email = $(this).closest("div").find(".contactEmail").val();
		 var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{1,8}$/i;

	   if($(".checkBoxContactId").is(":checked")==true)
			delErrFlag = false;
	   if($(".checkBoxContactId").is(":checked")==false)
		  delErrFlag = true;
			
		else
		{
			
			if($.trim(email) == "")
				 emailEmptyFlag = true;
		
			else if(!emailRegEx.test(email))
				invalidEmailFlag = true;

			if($.trim(accountReceName) == "")
				contactNameEmptyFlag = true;
		
		 }
		 
	  }
		
	});

if(!invalidEmailFlag)
{
	$(".checkBoxContactId").each(function(){
	
		if($(this).is(":checked"))
		{
			var eMail = $(this).closest("div").find(".contactEmail").val();
			if(emailArray.indexOf(eMail) == -1)
				emailArray.push(eMail);

			else
			{	$(this).closest("div").css("background","yellow");
				emailDupFlag = true;
			}
		
		}
		
	});
}
	if(emailEmptyFlag && contactNameEmptyFlag){
		$("#accountreceivableProfilesDialog").find("#errorDiv").attr("tabindex",0).focus();
		$("#errorDiv").text("Please Enter Name and Email.").addClass("emailErrorDiv");
		return;
	} 
    else if(emailEmptyFlag)
	{
		$("#accountreceivableProfilesDialog").find("#errorDiv").attr("tabindex",0).focus();
		$(this).closest("div").find(".contactEmail").css("border","red");
		$("#errorDiv").text("Please Enter Email.").addClass("emailErrorDiv");
		return;
	}
	else if(invalidEmailFlag)
	{
		$("#accountreceivableProfilesDialog").find("#errorDiv").attr("tabindex",0).focus();
		$("#errorDiv").text("Please Enter Valid Email.").addClass("emailErrorDiv");
		return;
	}
	else if(emailDupFlag)
	{
		$("#accountreceivableProfilesDialog").find("#errorDiv").attr("tabindex",0).focus();
		$("#errorDiv").text("Duplicate Email Exists.").addClass("emailErrorDiv");
		return;
	}
	else if(delErrFlag)
	{
		$("#accountreceivableProfilesDialog").find("#errorDiv").attr("tabindex",0).focus();
		$("#errorDiv").text("Please Select Email.").addClass("emailErrorDiv");
		return;
	}
	else if(contactNameEmptyFlag){
	$("#accountreceivableProfilesDialog").find("#errorDiv").attr("tabindex",0).focus();
	$("#errorDiv").text("Please Enter Name.").addClass("emailErrorDiv");
		return;
	}

	else
	{
		$("#accountreceivableProfilesDialog").find("#errorDiv").removeAttr("tabindex");
		$("#errorDiv").empty();
		$("#errorDiv").removeClass("emailErrorDiv");
	
	$(".checkBoxContactId").each(function(){
	
		if($(this).is(":checked"))
		{
			var obj1 = {};
		var contactName = $(this).closest("div").find(".contactName").val();
	    var contactEmail = $(this).closest("div").find(".contactEmail").val();
		
		obj1["contactName"] = contactName;
		obj1["contactEmail"] = contactEmail;
		obj.namesAndemailsArray.push(obj1);
		}


	});

	
	$('#ajaxImage').css('display','block');
	
	$.ajaxSetup({
		   jsonp: null,
		   jsonpCallback: null
		});

	    $.ajax({
		type:'POST',
		url: 'send-mail.action?sendEmailToAccountReceivables',
		dataType: 'json',
		data: {name : name ,data :JSON.stringify(obj)},
		success: function(result){
		   $('#ajaxImage').css('display','none');
			  alert("Your mail sent successfully.");
			  $('#accountreceivableProfilesDialog').dialog('close');
			
    
		 },
		error:function() { 
			  
		  }
	});

}

	
}
